import React, { useState, useEffect } from 'react';
import { Link, Route } from 'react-router-dom'
import { Button } from 'antd';
import { PlusCircleOutlined, SearchOutlined } from '@ant-design/icons';
import { Table, Input, InputNumber, Popconfirm, Form, Typography } from 'antd';
import { ListStyle } from './style'
import Add from '../Add'
import { getStorage, setStorage } from '@/utils/LocalStorage'
import { goodslist } from '@/model/goodsModel.js'

import { useSelector } from 'react-redux'

const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
}) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{
                        margin: 0,
                    }}
                    rules={[
                        {
                            required: true,
                            message: `请输入${title}!`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};



const IndexCmp = () => {
    /* 商品状态 */
    const [stateFlag, setStateFlag] = useState(true);
    const [form] = Form.useForm();
    const [data, setData] = useState([]);
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record) => record.key === editingKey;

    // 在redux中取数据
    const dataRedux = useSelector(state => state.getIn(['goods'])).toJS()

    const [List, setGoodsList] = useState([])
    const originData = getStorage("goodsMessage") ? JSON.parse(getStorage("goodsMessage")) : [];

    async function goodsList() {
        let data = await goodslist()
        data = data.data.data
        let list = [...data, ...originData]
        setGoodsList(list)
        setData(list)

    }

    useEffect(() => {
        goodsList()
        // 打印在 redux中取出的数据
        // console.log(dataRedux.goodsList);
    }, [])

    const cancel = () => {
        setEditingKey('');
    };

    const edit = (record) => {
        form.setFieldsValue({
            goodsNum: '',
            goodsName: '',
            goodsTime: '',
            ...record,
        });
        setEditingKey(record.key);
    };

    const save = async (key) => {
        try {
            const row = await form.validateFields();
            const newData = [...data];
            const index = newData.findIndex((item) => key === item.key);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                // 存放修改之后的数据
                // setStorage('goodsMessage', JSON.stringify(newData))
                setEditingKey('');
            } else {
                newData.push(row);
                setData(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    const columns = [
        {
            title: '商品编号',
            dataIndex: 'goodNum',
            width: '8%',
            editable: false,
            id: 1
        },
        {
            title: '商品名称',
            dataIndex: 'goodName',
            editable: true,
            id: 2
        },
        {
            title: '上架时间',
            dataIndex: 'goodTime',
            width: '10%',
            editable: true,
            id: 3
        },
        {
            title: '商品价格',
            dataIndex: 'goodPrice',
            width: '8%',
            editable: true,
            id: 4
        },
        {
            title: '商品品牌',
            dataIndex: 'goodBrand',
            editable: true,
            id: 5
        },
        {
            title: '商品属性',
            dataIndex: 'goodAttribute',
            editable: true,
            id: 6
        },
        {
            title: '库存状态',
            dataIndex: 'goodStock',
            width: '8%',
            editable: true,
            id: 7
        },
        {
            title: "商品状态",
            editable: false,
            width: '10%',
            id: 8,
            render: () => (
                <>
                    <Button type="primary" onClick={(evt) => {

                        setStateFlag(pre => {
                            pre = !pre;
                            pre ? evt.target.style.backgroundColor = "blue" : evt.target.style.backgroundColor = "red";
                            evt.target.innerText = pre ? "上架中" : "下架中";
                            return pre;
                        });

                    }}>
                        上架中
                    </Button>
                </>
            )
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: '15%',
            render: (_, record) => {
                const editable = isEditing(record);
                <button>000</button>
                return editable ? (
                    <span>
                        <a
                            href="javascript:void(0);"
                            onClick={() => save(record.key)}
                            style={{
                                marginRight: 8,
                            }}
                        >
                            完成
                    </a>
                        <Popconfirm title="确定取消？" onConfirm={cancel}>
                            <a>取消</a>
                        </Popconfirm>
                    </span>
                ) : (
                    <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                        操作
                    </Typography.Link>

                );
            },

        },
    ];

    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }

        return {
            ...col,
            onCell: (record) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });

    ///
    return (
        <>
            <ListStyle>
                <div className="goodsTop">
                    <span>商品管理</span>
                /
                <span>商品列表</span>
                </div>
                <hr />

                <div className="box">
                    <div className="goodsSearchBox">
                        <label>
                            <span>商品编号</span>
                            <Input placeholder="请输入商品编号" />
                        </label>
                        <label>
                            <span>商品名称</span>
                            <Input placeholder="请输入商品名称" />
                        </label>
                        <label>
                            <span>商品编品牌</span>
                            <Input placeholder="请输入商品品牌" />
                        </label>
                        <label>
                            <span>商品状态</span>
                            <Input placeholder="上架" />
                        </label>
                    </div>

                    <div className="btns">
                        <Button type="primary" icon={<SearchOutlined />} className="searchBtn">
                            搜索
                        </Button>
                        <Button type="primary" icon={<PlusCircleOutlined />} className="addBtn">
                            <Link to='/home/add'>添加</Link>
                        </Button>
                    </div>
                </div>

                <div>

                    <Form form={form} component={false}>
                        <Table
                            components={{
                                body: {
                                    cell: EditableCell,
                                },
                            }}
                            bordered
                            dataSource={data}
                            columns={mergedColumns}
                            rowClassName="editable-row"
                            pagination={{
                                onChange: cancel,
                            }}
                        />
                    </Form>
                </div>
                <Route path="/home/add" component={Add} />
            </ListStyle>
        </>
    );
}

export default IndexCmp;
